/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.testis.testdriver.operations;

import org.testis.testdriver.AtofEnumaration.DebuggingMode;
import org.testis.testdriver.StepContainer;
import org.testis.testdriver.TestIterator;
import org.testis.testdriver.TestPart;
import org.testis.testdriver.TestStep;

/**
 *
 * @author barisergun
 */
public class TestPartOperationCalculateMaximumRunCount extends TestPartOperationDecorator {

    private TestPart partInUse;

    public TestPartOperationCalculateMaximumRunCount(TestPart testPart) {
        partInUse = testPart;
    }

    @Override
    public boolean runOperation(DebuggingMode mode) throws InterruptedException {
        if (super.runOperation(mode)) {
            return runSpecificBehaviour();
        } else {
            return false;
        }
    }

    /**
     * This method is used to drive the specific Tasks that belong to this decorator
     * operation.
     *
     * @return boolean the result of operation. This result will affect the operation
     * of linked decorator tasks.
     */
    private boolean runSpecificBehaviour() {

        TestIterator curItemIter = partInUse.createIter();
        curItemIter.init();
        int maxExpectedRun = 1;
        while (curItemIter.isDone()) {
            curItemIter.next();
            TestPart current = curItemIter.currentItem();
            if (current instanceof TestStep) {
                int tempMax = 1;
                TestStep curStep = (TestStep) current;
                if (curStep.getDataArrayAppliesToCase()) {
                    tempMax =  ((StepContainer) partInUse).getInvocationCount() *
                            curStep.getTestDataList().size();
                }else{
                    tempMax =  ((StepContainer) partInUse).getInvocationCount();
                }
                if (tempMax > maxExpectedRun) {
                    maxExpectedRun = tempMax;
                }

            } else if (current instanceof StepContainer) {// Only happens for TSG
                int tempMax = ((StepContainer) partInUse).getInvocationCount();
                if (tempMax > maxExpectedRun) {
                    maxExpectedRun = tempMax;
                }
            }

        }
        ((StepContainer)partInUse).setHowManyTimesWillContainerRun(maxExpectedRun);
        
        return true;
    }
}
